package com.xiaohao.employee_attendance.controller;

import com.xiaohao.employee_attendance.bean.Department;
import com.xiaohao.employee_attendance.bean.User;
import com.xiaohao.employee_attendance.service.DeptService;
import com.xiaohao.employee_attendance.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @author 小浩
 * @date 2019-03-04 15:30
 * @package com.xiaohao.employee_attendance.controller
 * @description
 */
@Controller
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    DeptService deptService;

    @RequestMapping("/user-login")
    public ModelAndView userLogin(User user, HttpSession httpSession) {
        ModelAndView modelAndView = new ModelAndView();
        User userByName = userService.findUserByAccount(user.getAccount());
        if (userByName == null) {
            modelAndView.addObject("fail", "用户名不正确！");
            modelAndView.setViewName("login");
            return modelAndView;
        } else {
            if (userByName.getPassword().equals(user.getPassword())) {
                System.out.println(userByName);
                httpSession.setAttribute("user", userByName);
                httpSession.setAttribute("loginDate", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒")));
                modelAndView.setViewName("redirect:main");
            } else {
                modelAndView.setViewName("login");
                modelAndView.addObject("fail", "密码不正确！");
            }
            return modelAndView;
        }
    }

    @RequestMapping("user/userSearch")
    public String userSearchView(@RequestParam(defaultValue = "0") int page, Model model) {
        List<Department> allDept = deptService.findAllDept();
        List<User> allUser = userService.findAllUser();
        model.addAttribute("dept", allDept);
        model.addAttribute("allUser", getUseByPage(page));
        return "user/userSearch";

    }

    @RequestMapping("user/userInsert")
    public String userInsert(Model model) {
        List<Department> allDept = deptService.findAllDept();
        model.addAttribute("dept", allDept);
        return "user/userInsert";

    }


    @RequestMapping("user/userSearchByNameAnddept")
    @ResponseBody
    public List<User> findUserByNameAndDept(String name, String dept) {
        System.out.println(name);
        System.out.println(dept);
        List<User> users = null;
        if (name == "") {
            users = userService.findUserByDept(dept);
        }
        if (dept == "") {
            users = new ArrayList<>();
            users.addAll(userService.findUserByName(name));
        }
        if (name != "" && dept != "") {
            users = userService.findUserByNameAndDept(name, dept);
        }

        return users;
    }


    @RequestMapping("user/userSearch-api")
    @ResponseBody
    public Page<User> getUseByPage(int num) {
        Page<User> allUserPage = userService.findAllUserPage(5, num);
        return allUserPage;
    }


    @RequestMapping("user/userUpdate")
    public String userUpdate(int id, Model model) {
        System.out.println(id);
        User userByAccount = userService.findUserById(id);
        model.addAttribute("user", userByAccount);
        model.addAttribute("dept", deptService.findAllDept());
        return "user/userUpdate";
    }


    @RequestMapping("user/deleteOne")
    @ResponseBody
    public void userUpdate(String account) {
        System.out.println(account);
        userService.deleteUser(account);
    }

    @RequestMapping("user/save")
    public String userUpdate(User user) {

        System.out.println("user" + user);
        User userById = userService.findUserById(user.getId());
        System.out.println("userById" + userById);
        if (userById == null) {
            user.setCreateTime(LocalDate.now());
            user.setMylevel(user.getUserType());
            userService.saveUser(user);
        } else {
            deptService.updateTotalNumber(userById.getDepartmentId(), -1);
            userById.setPassword(user.getPassword());
            userById.setName(user.getName());
            userById.setDepartmentId(user.getDepartmentId());
            userById.setSex(user.getSex());
            userById.setMobile(user.getMobile());
            userById.setBirthday(user.getBirthday());
            userById.setEmail(user.getEmail());
            userById.setUserType(user.getUserType());
            userById.setMylevel(user.getUserType());
            System.out.println("修改前" + userById.getDepartmentId());
            System.out.println("修改后" + user.getDepartmentId());
            userService.saveUser(userById);
            deptService.updateTotalNumber(user.getDepartmentId(), 1);
        }
        return "forward:userSearch";
    }


    @RequestMapping("user/insert")
    public String userInsert(User user) {
        user.setCreateTime(LocalDate.now());
        user.setMylevel(user.getUserType());
        userService.saveUser(user);
        deptService.updateTotalNumber(user.getDepartmentId(), +1);
        System.out.println(user);
        return "forward:userSearch";
    }

    @RequestMapping("user/login")
    public String login(HttpServletRequest request, HttpServletResponse response) {

        for (Cookie cookie : request.getCookies()) {
            if ("autoLogin".equals(cookie.getName())) {
                cookie.setValue("false");
                cookie.setMaxAge(0);
                response.addCookie(cookie);
                System.out.println("cookie清除");
            }
        }
        request.getSession().invalidate();

        return "logout";

    }

    @RequestMapping("user/userPasswordUpdate")
    public String userPasswordUpdate(HttpServletRequest request, Model model) {

        User user = (User) request.getSession().getAttribute("user");
        model.addAttribute("user", userService.findUserByAccount(user.getAccount()));
        model.addAttribute("depts", deptService.findAllDept());
        return "user/userPasswordUpdate";

    }


    @RequestMapping("user/userUpdateApi")
    public String userUpdateApi(User user) {

        User userByAccount = userService.findUserByAccount(user.getAccount());
        user.setId(userByAccount.getId());

        user.setCreateTime(userByAccount.getCreateTime());
        user.setMylevel(userByAccount.getMylevel());
        user.setUserType(userByAccount.getUserType());

        user.setDepartmentId(userByAccount.getDepartmentId());
        userService.saveUser(user);
        return "user/userPasswordUpdate";

    }


}
